package com.lris.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lris.constant.MessageConstant;
import com.lris.constant.StatusConstant;
import com.lris.dto.UsernameLoginDto;
import com.lris.exception.BaseException;
import com.lris.mapper.UserMapper;
import com.lris.pojo.User;
import com.lris.result.PageResult;
import com.lris.service.UserService;
import com.lris.vo.FriendVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @auther lris
 * @create 2023-09-10 01:55:40
 * @describe 服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final RedisTemplate<String, String> redisTemplate;


    /**
     * 登录
     * @param usernameLoginDto 登录参数
     * @return 登录返回参数
     */
    @Override
    public User login(UsernameLoginDto usernameLoginDto) {
        String MD5Password = SecureUtil.md5(usernameLoginDto.getPassword());
        log.info("密码加密过后:{}", MD5Password);
        User user = userMapper.findUser(usernameLoginDto.getUsername());

        if (usernameLoginDto.getCode().equals("1234")){  //方便调试

            return user;
        }
        if (user == null) {
            log.info("用户名为空");
            throw new BaseException(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
        }
        if (!user.getPassword().equals(MD5Password)) {
            log.info("实际用户名:{}", user.getPassword());
            throw new BaseException(MessageConstant.USERNAME_OR_PASSWORD_ERROR);
        }
        String redisCode = redisTemplate.opsForValue().get(usernameLoginDto.getCodeid());

        if (!usernameLoginDto.getCode().equals(redisCode)) {

            log.info("缓存验证码:{}", redisCode);
            log.info("用户输入验证码:{}", usernameLoginDto.getCode());
            throw new BaseException(MessageConstant.CODE_ERROR);
        }
        if (Objects.equals(user.getStatus(), StatusConstant.DISABLE)) {
            log.info("实际用户状态:{}", user.getStatus());
            throw new BaseException(MessageConstant.ACCOUNT_LOCKED);
        }
        redisTemplate.delete(usernameLoginDto.getCodeid());
        return user;
    }

    /**
     * 模糊匹配
     *
     * @param search 查询条件
     * @return
     */
    @Override
    public PageResult findUserFriend(Integer page,Integer pageSize , String search) {
        PageHelper.startPage(page, pageSize);
       Page<FriendVo> Page  =userMapper.findFriend(search,search,search);
        PageResult pageResult = new PageResult();
        pageResult.setRecords(Page.getResult());
        pageResult.setTotal(Page.getTotal());
        return pageResult;
    }






}
